package com.g17.virtualpetbackend.controller;

import com.g17.virtualpetbackend.entity.User;
import com.g17.virtualpetbackend.service.UserService;
import com.g17.virtualpetbackend.utilty.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public List<User> getUser(@RequestParam(name = "id", required = false) Long id) {
        List<User> users;
        if (id==null)
        {
            users = userService.findAllUsers(); //all users
        }
        else
        {
            Optional<User> userById = userService.findUserById(id); // user match id
            //avoid internal server error
            User user = userById.orElseGet(() -> new User(null, null, null, null));
            users = new ArrayList<>();
            users.add(user);
        }
        return users;
    }

    @PostMapping("/user")
    public Response changeUser(@RequestParam(name = "id", required = false) Long id, @RequestParam("username") String username, @RequestParam("password") String password, @RequestParam(name = "type", required = false) Integer type)
    {
        User user;
        if (id==null)
        {
            //create
            user = userService.createUser(username, password);
        }
        else
        {
            //update
            user = userService.updateUser(id, username, password, type);
        }

        if(user!=null)
        {
            return new Response(user.getId(),Response.OK);
        }
        else
        {
            return new Response(Response.ERROR_ID,Response.ERROR);
        }
    }

    @DeleteMapping("/user")
    public Response deleteUser(@RequestParam(name = "id") Long id)
    {
        User user = userService.deleteUserById(id);
        if(user!=null)
        {
            //delete success, all attribute of user is set to null
            return new Response(id, Response.OK);
        }
        else
        {
            return new Response(Response.ERROR_ID,Response.ERROR);
        }
    }
}
